package app.controllers;

import app.models.Usuario;
import app.services.LogService;
import app.services.UsuarioService;
import app.session.UserSession;
import app.util.Constants;
import app.util.Credentials;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

/**
 * @author Douglas Fernandes
 * @since 25/11/2013
 */

@Resource
public class LoginController extends Controller {

    private Result result;
    private UserSession userSession;
    private UsuarioService usuarioService;
    private LogService logService;
    
    public LoginController(Result result, UserSession userSession,
    		UsuarioService usuarioService, LogService logService) {
    	
        this.result = result;
        this.userSession = userSession;
        this.usuarioService = usuarioService;
        this.logService = logService;
    }

    @Get("/login")
    public void login() {}
    
    @Get("/loginFailed")
    public void loginFailed() {
    	result.include(Constants.ERRORS, bundle.getString("userOrPasswordIncorrect")).forwardTo(this).login();
    }
    
    @Get("/autenticar/tablet/{macAddress}")
    public void autenticar(String macAddress) { }

    @Get("/autenticar")
    public void autenticar() {
    	
    	Usuario user = usuarioService.autentication(Credentials.username, Credentials.password);
    	
	    userSession.setUser(user);
	    
	    logService.createLog(Constants.LOGIN + user.getId());
	    	
	    Credentials.username = null;
	    Credentials.password = null;
    	
    	result.forwardTo(IndexController.class).index();
    }

    @Get("/logout")
    public void logout() {
    	
    	logService.createLog(Constants.LOGOUT + Credentials.idUsuario);
    	
    	Credentials.idUsuario = null;
    	
        userSession.logout();
        
        result.forwardTo(this).login();
    }
    
}